package com.simple.auth.event.listener;

import com.simple.auth.enums.AuthType;
import com.simple.auth.event.AuthSuccessEvent;
import com.simple.common.utils.IpUtils;
import com.simple.framework.core.domain.BaseUser;
import com.simple.system.domain.entity.SysUser;
import com.simple.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @Description 登录成功事件监听器
 * @Author xiaoke
 * @Date 2024/8/10 18:00
 * @Version 1.0
 */
@Slf4j
@Service
public class AuthSuccessEventListener implements ApplicationListener<AuthSuccessEvent> {

    private final SysUserService sysUserService;
    private final HttpServletRequest request;

    public AuthSuccessEventListener(SysUserService sysUserService, HttpServletRequest request) {
        this.sysUserService = sysUserService;
        this.request = request;
    }


    @Override
    public void onApplicationEvent(AuthSuccessEvent event) {
        log.info("监听到{}登录事件：{}", event.getAuthType(), event.getBaseUser());
        if (event.getAuthType() == AuthType.SYSTEM) {
            haneldSystem(event.getBaseUser());
        }
    }

    /**
     * 处理系统登录成功事件
     *
     * @param baseUser 基础用户信息
     */
    private void haneldSystem(BaseUser baseUser) {
        SysUser sysUser = new SysUser();
        sysUser.setId(baseUser.getId());
        sysUser.setLoginIp(IpUtils.getIpAddr(request));
        sysUser.setLoginDate(LocalDateTime.now());
        sysUserService.updateByLogin(sysUser);
        //更新用户ip城市
        sysUserService.updateIpCityById(baseUser.getId());
    }
}
